package main

import (
	"cross-shard-channel/common"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"github.com/eywa-protocol/bls-crypto/bls"
	"time"
)

// key and signature from json to byte
func MarshalTest() {
	var msg = []byte("123")
	privateKey, publicKey := bls.GenerateRandomKey()
	sig := privateKey.Sign(msg)
	res := sig.Verify(publicKey, msg)

	println("before = ", res)

	fmt.Println("pr = ", privateKey)
	fmt.Println("pu = ", publicKey)

	str1, _ := privateKey.MarshalJSON()
	str2, _ := publicKey.MarshalJSON()

	fmt.Println("str1:", string(str1))
	fmt.Println("str2:", string(str2))

	var pr bls.PrivateKey
	var pu bls.PublicKey

	pr, _ = bls.UnmarshalPrivateKey(str1)
	// _ = pr.UnmarshalJSON(str1)
	_ = json.Unmarshal(str2, &pu)

	sig2 := pr.Sign(msg)
	res2 := sig2.Verify(pu, msg)

	println("after = ", res2)
}

// 多重签名测试
func MulSigTest() {
	privateKey, publicKey := bls.GenerateRandomKey()
	fmt.Println(publicKey)
	fmt.Println(privateKey)

	priv0, pub0 := bls.GenerateRandomKey()
	priv1, pub1 := bls.GenerateRandomKey()
	priv2, pub2 := bls.GenerateRandomKey()

	msg := []byte("123")

	sig0 := priv0.Sign(msg)
	sig1 := priv1.Sign(msg)
	sig2 := priv2.Sign(msg)
	genuine := sig0.Aggregate(sig1).Aggregate(sig2).Verify(pub0.Aggregate(pub2).Aggregate(pub1), msg)

	println(genuine)
}

func utxoTest() {
	// create test
	_, pu := bls.GenerateRandomKey()
	txid := []byte("123")
	balance := int(12)

	utxo := common.NewUTXO(pu, txid, balance)
	utxo.Show()

	str, _ := json.Marshal(utxo)

	println("success marshal?")

	var u common.UTXO
	_ = json.Unmarshal(str, &u)
	u.Show()
}

func TransactionTest() {
	common.TxTest()
}

func sha256Test() {
	str := "test hash.."
	s_ob := sha256.New()
	s_ob.Write([]byte(str))
	r := s_ob.Sum(nil)
	fmt.Printf("%x\n", r)
}

func KeyGenerateTest() {
	t1 := time.Now() //获取本地现在时间

	for i := 0; i < 1000; i++ {
		_, _ = bls.GenerateRandomKey()
	}

	t2 := time.Now()
	d := t2.Sub(t1) //两个时间相减
	fmt.Println(d)

	_, pu := bls.GenerateRandomKey()
	b := pu.Marshal()
	a := int(b[0])
	println("pu first char = ", a)
}

func main() {
	fmt.Println("Hello, World!")

	KeyGenerateTest() // key generate test

	// sha256Test()

	// MarshalTest()
	// UTXO test()
	// TransactionTest()

}
